import 'package:base_flutter/base_flutter.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'dart:io';

class SpeakTextService{
  static FlutterTts flutterTts = FlutterTts();

  static List<String> _voicePools = [];

  static int _currentPlayIndex = 0;

  static var isSpeaking = false;

  static Future<void> initTts() async {
    await flutterTts.setLanguage("zh-CN");

    await flutterTts.setSpeechRate(0.5);

    await flutterTts.setVolume(1.0);

    await flutterTts.setPitch(0.5);

    await flutterTts.awaitSpeakCompletion(true);
    
    if(Platform.isAndroid){
      var engine =  await flutterTts.getEngines;

      Log.d("currentEngine", engine);
    }

    flutterTts.startHandler = (){
      isSpeaking = true;
    };

    flutterTts.completionHandler = (){
      isSpeaking = false;
      if(_currentPlayIndex==_voicePools.length-1){
        clearAll();
      }else{
        _currentPlayIndex++;
        var voice = _voicePools[_currentPlayIndex];
        flutterTts.speak(voice);
      }
    };

    flutterTts.errorHandler = (error){
      isSpeaking = true;
    };

    flutterTts.cancelHandler = (){
      isSpeaking = true;
    };
  }

  static void clearAll(){
    _currentPlayIndex = 0;
    _voicePools.clear();
    flutterTts.stop();
  }

  static void addVoice(String voiceText){
    if(!_voicePools.contains(voiceText)){
      _voicePools.add(voiceText);
      if(!isSpeaking){
        flutterTts.speak(_voicePools[_currentPlayIndex]);
      }
    }
  }

  static void stop(){
    clearAll();
  }

  static void pause(){
    flutterTts.stop();
  }

  static void resume(){
    if(_voicePools.isNotEmpty){
      var voice = _voicePools[_currentPlayIndex];
      flutterTts.speak(voice);
    }
  }

  static void speak(String text) {
    flutterTts.speak(text);
  }

}